import java.security.MessageDigest

public class Md5Computer extends Pacx {
    
    Md5Computer() {
        super()
        
    }

    public static void main(String[] args) {
        def mc = new Md5Computer()
        mc.run()
        mc.sql.close()
    }
    
    public void run() {
        print "=== Computing package md5..."
        def counter = 0
        def home = new File(extractionDir)
        def dirs = home.listFiles()
        def set = new TreeSet()
        for (dir in dirs)
           set.add(dir)
        for (dir in set) {
            if (dir.isDirectory()) {
                def pkgs = dir.listFiles()
                for (pkg in pkgs) {
//                    if (counter < 10) {
                        def pkgName =  pkg.getName()
                        def tmpFile = new File(extractionDir+"/"+pkg.getName()+".txt")
                        tmpFile.setText("")
                        tmpFile.setText(pkg.getName())
                        def md5sum = generateMD5(tmpFile)
                        def query = "update PACKAGES set md5sum=? where package=?"
                        sql.execute(query, [md5sum,pkgName])
                        //println "   "+md5sum+" "+pkgName
                        tmpFile.delete()
                        counter++
//                    }
                }
                
            }
            
        }
        
        
    }
    
    def generateMD5(final file) {
        MessageDigest digest = MessageDigest.getInstance("MD5")
        file.withInputStream(){
        
        is->
            byte[] buffer = new byte[8192]
            int read = 0
               while( (read = is.read(buffer)) > 0) {
                      digest.update(buffer, 0, read);
                  }
              }
            byte[] md5sum = digest.digest()
            BigInteger bigInt = new BigInteger(1, md5sum)
            return bigInt.toString(16)
     }

}